

// Start position for the map (hardcoded here for simplicity,
// but maybe you want to get from URL params)
// http://search.twitter.com/search.json?q=?&geocode=40.713975%2C-74.007182%2C1km
var lat=40.713975;
var lng=-74.007182;
var latlng;
var zoom=15;
var myOptions, map; //complex object of type OpenLayers.Map
var markersArray = new Array();
var ringsArray = new Array();
var layerMarkers;
var lastPos;
var xmlhttp;

var d2r = Math.PI / 180;
var detectRadius = 0.08;
var detectCircleLat = detectRadius * 0.014483;  // Convert statute miles into degrees latitude
var clickCircleLat = 0.013 * 0.014483;  // Convert statute miles into degrees latitude
var latlngbounds = new google.maps.LatLngBounds( );

var detectCircle = [];
var detectCrossLat, detectCrossLng;
var clickCircle;

var startMarker, endMarker;
var startImageLink = "img/tp1.gif";
var endImageLink = "img/tp2.gif";


var infoWindow, infoMarker ;

function init() {
    latlng = new google.maps.LatLng(lat, lng);
	var mapOpts = {
			zoom: zoom,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			disableDefaultUI: false,
			disableDoubleClickZoom: true,
			streetViewControl: false ,
			mapTypeControl: false,
			panControl: false,
			zoomControl: true
			
		};
    map = new google.maps.Map(document.getElementById("map_canvas"),
    		mapOpts);
  }




function initShowPosting() {
    
	var osmMapType = new google.maps.ImageMapType({
		getTileUrl: function(coord, zoom) {
			return "http://tile.openstreetmap.org/" +
			zoom + "/" + coord.x + "/" + coord.y + ".png";
		},
		tileSize: new google.maps.Size(256, 256),
		isPng: true,
		alt: "OpenStreetMap layer",
		name: "OpenStreetMap"
	});

	var latlng = new google.maps.LatLng(lat, lng);
	var mapOpts = {
		zoom: zoom,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDefaultUI: false,
		disableDoubleClickZoom: true,
		streetViewControl: false ,
		mapTypeControl: false,
		panControl: false,
		zoomControl: true
		
	};
	map = new google.maps.Map(document.getElementById("map"), mapOpts);

	map.overlayMapTypes.insertAt(0, osmMapType);
	
	
	infoWindow = new google.maps.InfoWindow();
	infoMarker = new google.maps.Marker();
  
}




function initPosting() {
    
	var osmMapType = new google.maps.ImageMapType({
		getTileUrl: function(coord, zoom) {
			return "http://tile.openstreetmap.org/" +
			zoom + "/" + coord.x + "/" + coord.y + ".png";
		},
		tileSize: new google.maps.Size(256, 256),
		isPng: true,
		alt: "OpenStreetMap layer",
		name: "OpenStreetMap"
	});

	var latlng = new google.maps.LatLng(lat, lng);
	var mapOpts = {
		zoom: zoom,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDefaultUI: false,
		disableDoubleClickZoom: true,
		streetViewControl: false ,
		mapTypeControl: false,
		panControl: false,
		zoomControl: true
	};
	map = new google.maps.Map(document.getElementById("map"), mapOpts);

	map.overlayMapTypes.insertAt(0, osmMapType);

    google.maps.event.addListener(map, 'click', function(e) {
    	//setPoint(e);
      });

    // create Start Marker
 
    var startImage = new google.maps.MarkerImage(startImageLink,
    	      // This marker is 20 pixels wide by 32 pixels tall.
    	      new google.maps.Size(99, 62),
    	      // The origin for this image is 0,0.
    	      new google.maps.Point(0,0),
    	      // The anchor for this image is the base of the flagpole at 0,32.
    	      new google.maps.Point(99, 32));

    var endImage = new google.maps.MarkerImage(endImageLink,
  	      // This marker is 20 pixels wide by 32 pixels tall.
  	      new google.maps.Size(99, 62),
  	      // The origin for this image is 0,0.
  	      new google.maps.Point(0,0),
  	      // The anchor for this image is the base of the flagpole at 0,32.
  	      new google.maps.Point(0, 32));   
    
      
    startMarker = new google.maps.Marker({
    	draggable: true, 
    	title: 'Drag&drop me to first stop',
    	position: latlng,
        map: map,
        icon: startImage
    });
    
    google.maps.event.addListener(startMarker, 'dragend', function(e) {
    	DivObj = document.getElementById("startLat");
    	DivObj.value = startMarker.getPosition().lat(); 
    	
    	DivObj = document.getElementById("startlng");
    	DivObj.value = startMarker.getPosition().lng();     	

      });
    
    endMarker = new google.maps.Marker({
    	draggable: true, 
    	title: 'Drag&drop me to a following stop',
    	position: latlng,
        map: map,
        icon: endImage
    });
   
    google.maps.event.addListener(endMarker, 'dragend', function(e) {
    	DivObj = document.getElementById("endLat");
    	DivObj.value = endMarker.getPosition().lat(); 
    	
    	DivObj = document.getElementById("endlng");
    	DivObj.value = endMarker.getPosition().lng();     	

      });   
}




function doAjaxShowPosting(id){

	 $.getJSON(id+'/showposting.map', function(data) {
		  showPosting(data);
	 });
}

function doAjaxShowGeoNames()
{
	 $.getJSON('showall.map', function(data) {
		  showAllGeoNsmes(data);
	 });
}

function doAjaxShowAllPoints(){

	 $.getJSON('showall.map', function(data) {
		  showAllPoints(data);
	 });
} 

function doAjaxShowAllActivities(){

	 $.getJSON('showallactivities.map', function(data) {
		 showAllActivities(data);
	 });
} 


function showAllActivities(data)
{
	$.each(data, function() {
	    //alert(this.body); 
    	var myLatlng = new google.maps.LatLng(this.lat,this.lng);
    	var infoWindowX = new google.maps.InfoWindow();
    	var infoMarkerX = new google.maps.Marker();
    	
    	//alert(1); 
    	//infoWindowX.close();
    	infoWindowX.setContent(this.body);
    	//alert(2);
    	infoMarkerX.setMap(map);
    	//alert(3);
    	infoMarkerX.setPosition(myLatlng);
    	//alert(4);
    	//infoWindowX.open(map,infoMarkerX);
    	//alert(5);
    	
   });
}

function showPosting(data)
{
	var myLatlng = new google.maps.LatLng(data.lat,data.lng);
	
	infoWindow.close();
	infoWindow.setContent(data.body);

	infoMarker.setMap(map);
	infoMarker.setPosition(myLatlng);

	infoWindow.open(map,infoMarker);

}

function showAllGeoNsmes(data)
{
    $.each(data, function() {
  
        var marker = new google.maps.Marker({
        	draggable: true, 
        	title: this.memo,
        	draggable: false,
        	position: new google.maps.LatLng(this.lat, this.lng),
            map: map
        });
    	
    });
}

function showAllPoints(data)
{
    $.each(data, function() {
  
    	drawCircle(document.getElementById("map"), 
    				map, 
    				new google.maps.LatLng(this.lat, this.lng), 
    				this.radius);
    });
}


function hideAllPoints()
{
    //alert(detectCircle);
	$.each(detectCircle, function() {
  
    	this.setMap(null);
    });
}


function setPoint(e)
{
	//alert(e.latLng.lat());
	DivObj = document.getElementById("lat");
	DivObj.value = e.latLng.lat(); 
	//alert(DivObj.value);
	
	DivObj = document.getElementById("lng");
	//DivObj.innerHTML= e.latLng.lng();
	DivObj.value = e.latLng.lng();	
	
	
	var selObj  = document.getElementById("radius");
	var selIndex = selObj.selectedIndex;

	hideAllPoints();
	
	drawCircle(document.getElementById("map"), map, e.latLng, selObj.options[selIndex].value);
}

function setRadius()
{
	deleteCircle();
	
	var lat = document.getElementById("lat").Value;
	var lng = document.getElementById("lng").Value;
	
	var selObj  = document.getElementById("radius");
	var selIndex = selObj.selectedIndex;
	
	drawCircle(document.getElementById("map"), 
						map, 
						new google.maps.LatLng(lat, lng), 
						selObj.options[selIndex].value);
}



function drawCircle(canvas, map, point, detectRadius) {
	
	var detectCircleLat = detectRadius * 0.014483;
	var circleLng = detectCircleLat / Math.cos(point.lat() * d2r);
	var circleLatLngs = new Array();
	var numPoints = 120;

	// 2PI = 360 degrees, +1 so that the circle is closed
	for (var i = 0; i < numPoints + 1; i++) { 
		var theta = Math.PI * (i / (numPoints / 2)); 
		var vertexLat = point.lat() + (detectCircleLat * Math.sin(theta)); 
		var vertexLng = parseFloat(point.lng()) + parseFloat((circleLng * Math.cos(theta)));
		var vertextLatLng = new google.maps.LatLng(vertexLat, vertexLng);
		circleLatLngs.push(vertextLatLng);
		//latlngbounds.extend(vertextLatLng);
	}

	var circle = new google.maps.Polygon({
		paths: circleLatLngs,
		strokeColor: "#339900",
		clickable : false,
		fillColor: "#339900",
		fillOpacity: 0.2
	});
	
	circle.setMap(map);
	detectCircle.push(circle);
	
}

// user move the map center to a location
function moveToLocation()
{
	var DivObj; 
	var newLat = map.getCenter().lat(); 
	var newLng = map.getCenter().lng(); 
	
	DivObj = document.getElementById("mylat");
	DivObj.innerHTML="<font size=2> lat: "+ newLat +"</font>";
	DivObj.Value = newLat; 

	DivObj = document.getElementById("mylng");
	DivObj.innerHTML="<font size=2> lng: "+ newLng +"</font>";
	DivObj.Value = newLng; 
	

	deleteDetectCircle();
	deleteClickCircle();
	//drawDetectCircle(document.getElementById("map"), map, map.getCenter());
	reloadAreaMsg();
	
}




function deleteCircle()
{
	if(detectCircle)
		detectCircle.setMap(null);
	if(detectCrossLat)	
		detectCrossLat.setMap(null);
	if(detectCrossLng)
		detectCrossLng.setMap(null);
	
}

function drawDClickCircle(canvas, map, point) {
	var circleLng = clickCircleLat / Math.cos(point.lat() * d2r);
	var circleLatLngs = new Array();
	var numPoints = 100;

	// 2PI = 360 degrees, +1 so that the end points meet
	for (var i = 0; i < numPoints + 1; i++) { 
		var theta = Math.PI * (i / (numPoints / 2)); 
		var vertexLat = point.lat() + (clickCircleLat * Math.sin(theta)); 
		var vertexLng = parseFloat(point.lng()) + parseFloat((circleLng * Math.cos(theta)));
		var vertextLatLng = new google.maps.LatLng(vertexLat, vertexLng);
		circleLatLngs.push(vertextLatLng);
		latlngbounds.extend(vertextLatLng);
	}

	clickCircle = new google.maps.Polygon({
		paths: circleLatLngs,
		strokeColor: "#FFFF00",
		fillColor: "#FFFF00",
		fillOpacity: 0.2
	});

	clickCircle.setMap(map);
}

function deleteClickCircle()
{
	if(clickCircle)
		clickCircle.setMap(null);
}

function checkLogin(loginId,loginName){

	var DivObj = document.getElementById("login");
	
	if (loginId!=0){
		
		DivObj.innerHTML="&nbsp;<b>Hello, &nbsp;<font size='3' color='#000099'><i>"+loginName+"&nbsp;</i></font><i><font size=2>(<a href='logout.map'>Logout</a>)</font></i>&nbsp;&nbsp;&nbsp;&nbsp;<a href='showallpostings.map'>All Journals</a></b>";

		}
}
